!(function (doc, win) {

    var docEl = doc.documentElement,
        isIOS = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
        metaEl = doc.querySelector('meta[name="viewport"]'),
        dpr = isIOS ? Math.min(win.devicePixelRatio, 3) : 1,
        dpr = window.top === window.self ? dpr : 1, //iframe
        clearClock,
        deviceWidth,
        resizeAble = true;

    //移除已有viewport，完全自定义
    if (metaEl) metaEl.parentNode.removeChild(metaEl);
    metaEl = doc.createElement('meta');
    metaEl.setAttribute('name', 'viewport');
    metaEl.setAttribute('content', 'width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no,shrink-to-fit=no, viewport-fit=cover');
    docEl.firstElementChild.appendChild(metaEl);

    function remLayout() {
        this.dpr = win.devicePixelRatio;
        this.ratio = 750;
    }

    remLayout.prototype = {

        recalc: function () {
            deviceWidth = docEl.clientWidth;
            if (deviceWidth / dpr > 750) deviceWidth = 750 * dpr;
            return this.rootSize = docEl.style.fontSize = 100 * (deviceWidth / this.ratio) + 'px';
        },

        setRatio: function (v) {
            this.ratio = v;
            return this.recalc();
        },

        resizeAble: function (bool) {
            if (bool) {
                (typeof bool === 'boolean') ? resizeAble = bool : console.warn('请传入一个布尔值')
            } else {
                return resizeAble = !resizeAble;
            }
        },

        remToPx: function (v) {
            return deviceWidth * (v * 100 / this.ratio);
        },

        pxToRem: function (v) {
            return v / (deviceWidth * 100) * this.ratio;
        }

    }

    var remLayout = new remLayout();

    remLayout.recalc();

    if (!doc.addEventListener) return;

    resize = win.addEventListener('resize', function (e) {
        if (!resizeAble) return;
        clearTimeout(clearClock);
        setTimeout(function () {
            remLayout.recalc();
        }, 300);
    }, false);

    win.addEventListener('pageshow', function (e) {
        if (!resizeAble) return;
        if (e.persisted) { //如果是返回的
            clearTimeout(clearClock);
            setTimeout(function () {
                remLayout.recalc();
            }, 300);
        }
    }, false);

    if (typeof module != 'undefined' && module.exports) {
        module.exports = remLayout;
    }
    else if (typeof define == 'function' && define.amd) {
        define(function () {
            return remLayout;
        });
    }
    else {
        window.remLayout = remLayout;
    }

})
(document, window);